﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

public class AESUntil
{

    public static string key = "542D386D53A64E1E809ADB2486A3E076";
    public static string iv = "22CD9B5FBC194961";
    /// <summary>
    /// 加密
    /// </summary>
    /// <param name="plainText">待加密的明文</param>
    /// <returns></returns>
    public static string Encrypt(string plainText)
    {
        byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
        byte[] keyBytes = Encoding.UTF8.GetBytes(key);
        byte[] ivBytes = Encoding.UTF8.GetBytes(iv);

        using Aes aes = Aes.Create();
        aes.Key = keyBytes;
        aes.IV = ivBytes;

        using MemoryStream memoryStream = new MemoryStream();
        using CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
        cryptoStream.Write(plainBytes, 0, plainBytes.Length);
        cryptoStream.FlushFinalBlock();

        byte[] encryptedBytes = memoryStream.ToArray();
        string encryptedText = Convert.ToBase64String(encryptedBytes);

        return encryptedText;
    }

    /// <summary>
    /// 解密
    /// </summary>
    /// <param name="encryptedText">密文</param>
    /// <returns></returns>
    public static string Decrypt(string encryptedText)
    {
        byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
        byte[] keyBytes = Encoding.UTF8.GetBytes(key);
        byte[] ivBytes = Encoding.UTF8.GetBytes(iv);

        using Aes aes = Aes.Create();
        aes.Key = keyBytes;
        aes.IV = ivBytes;

        using MemoryStream memoryStream = new MemoryStream(encryptedBytes);
        using CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
        using StreamReader streamReader = new StreamReader(cryptoStream);
        string decryptedText = streamReader.ReadToEnd();

        return decryptedText;
    }
}